package com.eascs.loan.controller;

import java.math.BigDecimal;
import java.text.DecimalFormat;
import java.text.Format;
import java.util.Calendar;
import java.util.Date;
import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;

import com.eascs.admin.common.controller.BaseMasterViewController;
import com.eascs.admin.common.utils.StringUtils;
import com.eascs.admin.o2o.internal.util.StatusContexts;
import com.eascs.admin.o2o.loan.entity.O2oLoanapplyEntity;
import com.eascs.admin.o2o.loan.service.O2oLoanapplyService;
import com.eascs.app.dao.PageResult;
import com.eascs.common.util.DateUtils;
import com.eascs.common.util.StringUtil;
import com.eascs.common.util.UrlUtil;
import com.eascs.datalist.entity.O2oDataListEntity;
import com.eascs.datalist.service.impl.O2oDataListServiceImpl;
import com.eascs.loan.entity.O2oBankLoanData;
import com.eascs.loan.entity.O2oPaymentsPlan;
import com.eascs.loan.form.O2oLoanForm;
import com.eascs.loan.form.O2oPaymentsForm;
import com.eascs.loan.service.O2oLoanService;
import com.eascs.loan.service.O2oPaymentsService;
import com.eascs.loan.service.impl.O2oLoanServiceImpl;
import com.eascs.loan.service.impl.O2oPaymentsServiceImpl;
import com.eascs.site.page.PaginationInfo;
import com.eascs.site.page.SelectDataOption;
import com.eascs.site.view.ViewContext;
import com.eascs.site.view.button.AjaxButton;
import com.eascs.site.view.button.AjaxConfirmButton;
import com.eascs.site.view.button.Button;
import com.eascs.site.view.button.ButtonHelper;
import com.eascs.site.view.button.ShowButtonFilter;
import com.eascs.tag.MenuTag;

/**
 * @ClassName: O2oLoanController
 * @Description:
 * @author user
 * @date 2016年7月15日 上午10:22:00
 * @version V1.0
 */
@Controller
@RequestMapping("/bank")
public class O2oLoanController extends BaseMasterViewController {

	@Autowired
	O2oLoanService o2oLoanService;

	@Autowired
	O2oPaymentsService o2oPaymentsService;

	@Autowired
	private O2oLoanapplyService loanService;
	@Autowired
	private O2oPaymentsServiceImpl paymentServiceImpl;
	
	@Autowired
	private O2oLoanServiceImpl o2oLoanServiceImpl;
	

//	@Override
//	public void preHandle() {
//		super.preHandle();
//		 ViewContext.put(MenuTag.CURRENT_MENU_CODE, "afterLoanManage");
//	}

	/**
	 * @Title: loanList
	 * @Description: 银行放款数据列表
	 * @author user
	 * @param o2oLoanForm
	 * @return
	 * @return String
	 * @throws @date
	 *             2016年7月15日 上午10:21:23
	 */
	@SuppressWarnings("unused")
	@RequestMapping("/loan_list")
	public String index(O2oLoanForm o2oLoanForm) {
		ViewContext.put(MenuTag.CURRENT_MENU_CODE, "bankLoanData");
		o2oLoanForm.setPageSize(10);
		String o2opageUrl = "/bank/index";
		if (o2oLoanForm != null) {
			o2opageUrl = UrlUtil.appendUrl(o2opageUrl, "billCode", o2oLoanForm.getBillCode());
			o2opageUrl = UrlUtil.appendUrl(o2opageUrl, "loanBank", o2oLoanForm.getLoanBank());
			o2opageUrl = UrlUtil.appendUrl(o2opageUrl, "loanDate1", o2oLoanForm.getLoanDate1());
			o2opageUrl = UrlUtil.appendUrl(o2opageUrl, "loanDate2", o2oLoanForm.getLoanDate2());
			o2opageUrl = UrlUtil.appendUrl(o2opageUrl, "loanType", o2oLoanForm.getLoanType());
			o2opageUrl = UrlUtil.appendUrl(o2opageUrl, "loanerName", o2oLoanForm.getLoanerName());
			o2opageUrl = o2opageUrl + "&showPage=";
		} else {
			o2opageUrl = o2opageUrl + "?showPage=";
		}
		String oldpageUrl = "/bank/oldLoan_list";
		if (o2oLoanForm != null) {
			oldpageUrl = UrlUtil.appendUrl(oldpageUrl, "billCode", o2oLoanForm.getBillCode());
			oldpageUrl = UrlUtil.appendUrl(oldpageUrl, "loanBank", o2oLoanForm.getLoanBank());
			oldpageUrl = UrlUtil.appendUrl(oldpageUrl, "loanDate1", o2oLoanForm.getLoanDate1());
			oldpageUrl = UrlUtil.appendUrl(oldpageUrl, "loanDate2", o2oLoanForm.getLoanDate2());
			oldpageUrl = UrlUtil.appendUrl(oldpageUrl, "loanType", o2oLoanForm.getLoanType());
			oldpageUrl = UrlUtil.appendUrl(oldpageUrl, "loanerName", o2oLoanForm.getLoanerName());
			oldpageUrl = oldpageUrl + "&oldShowPage=";
		} else {
			oldpageUrl = oldpageUrl + "?oldShowPage=";
		}
		ViewContext.put("o2opageUrl", o2opageUrl);
		ViewContext.put("oldpageUrl", oldpageUrl);
		ViewContext.put("vo", o2oLoanForm);
		return "bank/index";
	}

	/**
	 * @Title: addLoan
	 * @Description: 增加银行放款数据
	 * @author user
	 * @param o2oLoanForm
	 * @return
	 * @return String
	 * @throws @date
	 *             2016年7月15日 上午10:22:03
	 */
	@RequestMapping("/add_loan")
	public String addLoan(O2oLoanForm o2oLoanForm) {
		String bankLoanId = o2oLoanForm.getBankLoanId();
		O2oBankLoanData  o2oBankLoanData = o2oLoanServiceImpl.findEntity(bankLoanId); //先查出银行放款数据
		o2oLoanForm.setPayType(o2oBankLoanData.getPayType());
		o2oLoanForm.setBillCode(o2oBankLoanData.getBillCode());
		return common(o2oLoanForm, "add");
	}

	@RequestMapping("/edit_loan")
	public String editLoan(O2oLoanForm o2oLoanForm) {
		String bankLoanId = o2oLoanForm.getBankLoanId();
		O2oBankLoanData  o2oBankLoanData = o2oLoanServiceImpl.findEntity(bankLoanId); //先查出银行放款数据
		o2oLoanForm.setPayType(o2oBankLoanData.getPayType());
		o2oLoanForm.setBillCode(o2oBankLoanData.getBillCode());
		return common(o2oLoanForm, "edit");
	}

/*	@RequestMapping("/show_loan")
	public String showLoan(O2oLoanForm o2oLoanForm) {
		String bankLoanId = o2oLoanForm.getBankLoanId();
		O2oBankLoanData  o2oBankLoanData = o2oLoanServiceImpl.findEntity(bankLoanId); //先查出银行放款数据
		o2oLoanForm.setPayType(o2oBankLoanData.getPayType());
		o2oLoanForm.setBillCode(o2oBankLoanData.getBillCode());
		return common(o2oLoanForm, "show");
	}*/

	private String common(O2oLoanForm o2oLoanForm, String operType) {
		String returnMsg = "";
		boolean isExpireTime = isExpireTime(o2oLoanForm.getBillCode());
		String oldPaytype="";
		if(!isExpireTime){
			ViewContext.put("dateNotendDate", "提示：“最大计划还款时间不等于到期日”");
		}
		
		if (StringUtils.isNotEmpty(o2oLoanForm.getBillCode())) {
			List<Object[]> bill_list = null;
			if (operType.equals("edit")) {
//				if(o2oLoanForm.getBillCode().startsWith("O2O")){ //老系统数据以O2O开头
//					bill_list = o2oLoanService.getO2OBankData(o2oLoanForm.getBillCode()); 
//				}else{
					bill_list = o2oLoanService.getBankData(o2oLoanForm.getBillCode(),o2oLoanForm.getPayType());
//				}
				returnMsg = "/bank/add_loan";
			} else if (operType.equals("show")) {
//				if(o2oLoanForm.getBillCode().startsWith("O2O")){ //老系统数据以O2O开头
//					bill_list = o2oLoanService.getO2OBankData(o2oLoanForm.getBillCode()); 
//				}else{
					bill_list = o2oLoanService.getBankData(o2oLoanForm.getBillCode(),o2oLoanForm.getPayType());
//				}
				returnMsg = "/bank/show_loan";
			} else {
				bill_list = o2oLoanService.isBillCodeExists(o2oLoanForm.getBillCode(), null, null);
				returnMsg = "/bank/add_loan";
			}
			
			if ((bill_list != null && bill_list.size() > 0)) {
				Object[] o = bill_list.get(0);
				if (o[1] != null) {
					String loanerCard = (String) o[1];
					o2oLoanForm.setLoanerCard(loanerCard);
				}
				if (o[2] != null) {
					String loanerName = (String) o[2];
					o2oLoanForm.setLoanerName(loanerName);
				}
				if (o[3] != null) {
					String loanBank = (String) o[3];
					o2oLoanForm.setLoanBank(loanBank);
				}
				if (o[4] != null) {
					BigDecimal applyAmount = (BigDecimal) o[4];
					o2oLoanForm.setApplyAmount(applyAmount);
				}
				if (o[5] != null) {
					BigDecimal loanRate = (BigDecimal) o[5];
					o2oLoanForm.setLoanRate(loanRate);
				}

				if (o[6] != null) {
					BigDecimal loanAmount = (BigDecimal) o[6];
					o2oLoanForm.setLoanAmount(loanAmount);
				}
				if (o[7] != null) {
					int loanTerm = 0;
					if(o[7] instanceof  String){
						 loanTerm = Integer.parseInt((String)o[7]);
					}else{
						 loanTerm = (int) o[7];
					}
					o2oLoanForm.setLoanTerm(loanTerm);
				}
				if (o[8] != null) {
					String loanDate = "";
					if (operType.equals("edit") || operType.equals("show")) {
						if(o[8] instanceof Date){
							Date loan = (Date) o[8];
							loanDate = DateUtils.formateStandDate(loan);
						}else{
							loanDate = (String) o[8];
						}
					} else {
						loanDate = (String) o[8];
					}
					o2oLoanForm.setLoanDate(loanDate);
				}
				if (o[9] != null) {
//					if(o2oLoanForm.getBillCode().startsWith("O2O")){ //老系统数据以O2O开头
//						O2oLoanapplyEntity loan = new O2oLoanapplyEntity();
//						java.sql.Date endBankDate = (java.sql.Date) o[9];
//						loan.setEndBankDate(endBankDate);
//						ViewContext.put("loanEntity", loan);
//					}else{
						String loanBankCode = (String) o[9];
						o2oLoanForm.setLoanBankCode(loanBankCode);
//					}
				}
//				if(o2oLoanForm.getBillCode().startsWith("O2O")){ //老系统数据以O2O开头
//					if (o[10] != null) {
//						oldPaytype = (String) o[10];
//					}
//				}
			}
		}
		ViewContext.put("voo", o2oLoanForm);
		ViewContext.put("operType", operType);
		
		// 银行还款计划列表
		payMents(o2oLoanForm.getBillCode(), o2oLoanForm.getType(),o2oLoanForm.getPayType());
		
		if(o2oLoanForm.getBillCode().startsWith("O2O")){ //老系统数据以O2O开头
			ViewContext.put("payType",oldPaytype );
		}
		// 还款记录查询
		if (operType.equals("show"))
			hkHistory(o2oLoanForm.getBillCode());
		return returnMsg;
	}

	public void payMents(String billCode, String type,String payType) {
		O2oPaymentsForm o2oPaymentsForm = new O2oPaymentsForm();
		o2oPaymentsForm.setBillCode(billCode);
		o2oPaymentsForm.setPageSize(100);
		o2oPaymentsForm.setPayType(payType);
		PageResult<Object[]> pageResult = o2oPaymentsService.paymentsList(o2oPaymentsForm);
		String[] titles = { "贷款单号", "借款人姓名", "借款人证件号", "还款期数", "应还款日期", "剩余本金", "应还本金", "应还利息", "未还本金", "未还利息", "罚息", "状态" };
		String pageUrl = "/payments/payments_list";
		PaginationInfo paginationInfo = new PaginationInfo(pageResult, titles, pageUrl + "&showPage=");
		paginationInfo.setBuildPagingNavigation(false);
		paginationInfo.setFirstRenderColumnIndex(1);
		if (type.equals("edit")) {
			AjaxConfirmButton[] dealButton = new AjaxConfirmButton[] { new AjaxConfirmButton("删除", "/paymentsRest/delPayments?bill_code=" + billCode + "&payments_id=") };
			paginationInfo.setMoreButtons(dealButton);
		} else if (type.equals("show")) {
			if (StringUtil.isNotBlank(payType)) {
				AjaxButton[] hkButton = new AjaxButton[] { new AjaxButton("发起还款", "/paymentsRest/repayment?billCode=" + billCode + "&paymentsId=") };
				paginationInfo.setMoreButtons(hkButton);
			}
		}
		SelectDataOption[] selectDataOptions = { null, null, null, null, null, null, null, null, null, null, null, new SelectDataOption("REPAYMENT_STATUS") };
		paginationInfo.setSelectDataOptions(selectDataOptions);
		paginationInfo.setFormats(new Format[] { null, null, null, null, null, new DecimalFormat(",##0.00"), new DecimalFormat(",##0.00"), new DecimalFormat(",##0.00"), new DecimalFormat(",##0.00"), new DecimalFormat(",##0.00"), new DecimalFormat(",##0.00"), null });
		ViewContext.put("paginationInfo", paginationInfo);
		ViewContext.put("vo", o2oPaymentsForm);
		//ViewContext.put("payType", getLoantype(billCode));
		ViewContext.put("payType", payType);
		if (pageResult.getData().size() > 0) {
			ViewContext.put("upload", "upload");
		}

	}

	/**
	 * @Description: <p> 查询还款记录 </p>
	 * @author CXW
	 * @date 2016年9月8日 下午1:36:37
	 * @version V1.0
	 * @param billCode
	 * @return void
	 */
	public void hkHistory(String billCode) {
		O2oPaymentsForm o2oPaymentsForm = new O2oPaymentsForm();
		o2oPaymentsForm.setBillCode(billCode);
		o2oPaymentsForm.setPageSize(10);
		PageResult<Object[]> pageResult = o2oPaymentsService.repaymentsList(o2oPaymentsForm);
		String titles[] = { "对应期还款数", "应还日期", "实际还款日期", "还款本金", "还款利息", "罚息", "还款凭证", "流程状态" };// 
		AjaxButton start_upButton = new AjaxButton("发起流程", "/paymentsRest/start?id=");
		AjaxButton detailButton = new AjaxButton("详情", "/paymentsRest/recordView?billCode=" + billCode + "&referId=");
		
		AjaxButton editButton = new AjaxButton("编辑", "/paymentsRest/findRecord?recordId=");
		AjaxConfirmButton deleteButton = new AjaxConfirmButton("删除", "/paymentsRest/deleteRecord?recordId=");
		
		deleteButton.setShowButtonFilter(showBottun);
		editButton.setShowButtonFilter(showBottun);
		
		Button[] dealButton = new Button[] { start_upButton, detailButton, editButton, deleteButton };
		PaginationInfo o2oPagingInfo = new PaginationInfo(pageResult, titles);
		o2oPagingInfo.setTitleButtons(new Button[]{null,null,null,null,null,null,ButtonHelper.createOpenButton(null, "/file/download?datalistno={9}")});
		o2oPagingInfo.setMoreButtons(dealButton);
		o2oPagingInfo.setBuildPagingNavigation(false);
		o2oPagingInfo.setFirstRenderColumnIndex(1);
		o2oPagingInfo.setBuildRowNumber(true);
		SelectDataOption[] selectDataOptions = { null, null, null, null, null, null, null, new SelectDataOption("PAY_STATUS") };
		o2oPagingInfo.setSelectDataOptions(selectDataOptions);
		ViewContext.put("o2oPagingInfo", o2oPagingInfo);
	}
	
	/**
	 * 是否显示按钮过滤器
	 */
	public ShowButtonFilter showBottun = new ShowButtonFilter() {
		
		@Override
		public boolean filter(Object param) {
			Object[] params = (Object[]) param;
			if (params[7].equals(StatusContexts.O2O_NEW)) {
				return true;
			} else {
				return false;
			}
		}
	};

	@Autowired
	private O2oDataListServiceImpl o2oDataListService;

	/**
	 * @Description
	 * 				<p>
	 *              </p>
	 * @author CXW
	 * @date 2016年8月26日 下午5:48:18
	 * @version V1.0
	 * @param
	 * @return BaseRestResult<String>
	 */
	@RequestMapping("/repaymentFileDiv")
	public String repaymentFileDiv(String billCode, String paymentsId) {
		O2oLoanapplyEntity loanEntity = loanService.fingByBillCode(billCode);
		if (loanEntity != null) {
			ViewContext.put("loanapplyNo", loanEntity.getLoanapplyNo());
			List<O2oDataListEntity> o2oDataList = o2oDataListService.getByBillCodeDataList(loanEntity.getLoanapplyNo(), paymentsId);
			ViewContext.put("o2oDataList", o2oDataList);
		}
		ViewContext.put("paymentsId", paymentsId);
		return "bank/repaymentFileDiv";
	}

	/**
	 * @Description:
	 * 				<p>
	 *               </p>
	 * @author CXW
	 * @date 2016年9月6日 下午5:36:21
	 * @version V1.0
	 * @param billCode
	 * @return String
	 */
	public String getLoantype(String billCode) {
		O2oLoanapplyEntity loan = loanService.fingByBillCode(billCode);
		if (loan != null) {
			return loan.getLoanType();
		} else {
			return "BK";
		}
	}
	
	
	
	
	/**
	 * @Description:
	 * 				<p>
	 *               查询实际放款时间是否等于计划放款最后时间
	 *               </p>
	 * @author CXW
	 * @date 2016年9月18日 上午9:42:50
	 * @version V1.0
	 * @param billCode
	 * @return boolean
	 */
	public boolean isExpireTime(String billCode) {
		O2oLoanapplyEntity loan = loanService.fingByBillCode(billCode);
		ViewContext.put("loanEntity", loan);
		O2oPaymentsPlan payment = paymentServiceImpl.findByBillCode(billCode);
		if (null == loan || null == payment) {
			return false;
		} else {
			if (null == loan.getEndBankDate() || null == payment.getPaymentsDate()) {
				return false;
			}
			Calendar loanDate = Calendar.getInstance();
			loanDate.setTime(loan.getEndBankDate());
			Calendar paymentDate = Calendar.getInstance();
			paymentDate.setTime(payment.getPaymentsDate());
			boolean isSameYear = loanDate.get(Calendar.YEAR) == paymentDate.get(Calendar.YEAR);
			boolean isSameMonth = isSameYear && loanDate.get(Calendar.MONTH) == paymentDate.get(Calendar.MONTH);
			boolean isSameDate = isSameMonth && loanDate.get(Calendar.DAY_OF_MONTH) == paymentDate.get(Calendar.DAY_OF_MONTH);
			return isSameDate;
		}
	}
}
